import 'package:flutter/material.dart';
import 'package:flutter_openim_sdk/flutter_openim_sdk.dart';
import 'package:get/get.dart';
import 'package:openim_common/openim_common.dart';
import '../../../routes/app_navigator.dart';
import 'package:flutter_stripe/flutter_stripe.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

class GroupPaymentLogic extends GetxController {
  final groupInfo = Rxn<GroupInfo>();
  final groupFee = 0.0.obs;
  final isPaymentProcessing = false.obs;

  String? groupId;
  String? inviteCode;
  String? inviterUserId;
  final String paymentBaseUrl = Config.paymentBaseUrl;

  @override
  void onInit() {
    super.onInit();
    final args = Get.arguments as Map<String, dynamic>?;
    if (args != null) {
      groupInfo.value = args['groupInfo'] as GroupInfo?;
      groupId = args['groupId'] as String?;
      inviteCode = args['inviteCode'] as String?;
      inviterUserId = args['inviterUserId'] as String?;
      groupFee.value = args['groupFee'] as double? ?? 0.0;
    }
  }

  Future<void> payAndJoinGroup() async {
    if (groupId == null || groupFee.value <= 0) {
      IMViews.showToast('群组信息或费用无效');
      return;
    }
    try {
      isPaymentProcessing.value = true;

      if (Stripe.publishableKey.isEmpty && Config.stripePublishableKey.isNotEmpty) {
        Stripe.publishableKey = Config.stripePublishableKey;
        await Stripe.instance.applySettings();
      }

      final clientSecret = await _fetchPaymentIntentClientSecret();
      if (clientSecret.isEmpty || !clientSecret.contains('_secret_')) {
        IMViews.showToast('支付订单创建失败或密钥无效');
        return;
      }

      await Stripe.instance.initPaymentSheet(
        paymentSheetParameters: SetupPaymentSheetParameters(
          paymentIntentClientSecret: clientSecret,
          merchantDisplayName: 'Paxiy',
          // 为 Apple Pay 和 Google Pay 提供基本配置
          applePay: const PaymentSheetApplePay(
            merchantCountryCode: 'US',
          ),
          googlePay: const PaymentSheetGooglePay(
            merchantCountryCode: 'US',
            testEnv: true, // 如果是测试环境
          ),
          style: ThemeMode.system,
          allowsDelayedPaymentMethods: false,
        ),
      );

      try {
        await Stripe.instance.presentPaymentSheet();
      } on StripeException catch (e) {
        final msg = e.error.localizedMessage ?? e.error.message ?? '支付被取消或失败';
        IMViews.showToast(msg);
        return;
      }

      await _joinGroupAfterPayment();
    } catch (e) {
      IMViews.showToast('支付处理失败：$e');
    } finally {
      isPaymentProcessing.value = false;
    }
  }

  Future<String> _fetchPaymentIntentClientSecret() async {
    if (paymentBaseUrl.isEmpty) {
      IMViews.showToast('支付服务地址未配置');
      return '';
    }
    final uri = Uri.parse('$paymentBaseUrl/payment/create_group_intent');
    try {
      final resp = await http.post(
        uri,
        headers: {'Content-Type': 'application/json'},
        body: jsonEncode({
          'groupId': groupId,
          'userId': OpenIM.iMManager.userID,
          'amount': (groupFee.value * 100).round(),
          'currency': 'usd',
        }),
      );
      if (resp.statusCode == 200) {
        final data = jsonDecode(resp.body) as Map<String, dynamic>;
        return (data['clientSecret'] as String?) ?? '';
      } else {
        IMViews.showToast('创建支付订单失败，状态码：${resp.statusCode}');
        return '';
      }
    } catch (e) {
      IMViews.showToast('网络请求失败：$e');
      return '';
    }
  }

  /// 支付成功后加入群聊
  Future<void> _joinGroupAfterPayment() async {
    if (groupInfo.value == null || groupId == null) return;

    try {
      await LoadingView.singleton.wrap(
        asyncFunction: () async {
          await OpenIM.iMManager.groupManager.joinGroup(
            groupID: groupId!,
            reason: '通过邀请链接加入（已支付）',
            joinSource: 2,
          );

          final conversationInfo = ConversationInfo(
            conversationID: 'sg_$groupId',
            conversationType: ConversationType.group,
            userID: '',
            groupID: groupId,
            showName: groupInfo.value!.groupName,
            faceURL: groupInfo.value!.faceURL,
          );

          Get.back(); // 关闭支付页面
          AppNavigator.startChat(conversationInfo: conversationInfo);
        },
      );
    } catch (e) {
      Logger.print('加入群聊失败: $e');
      IMViews.showToast('加入群聊失败，请稍后重试');
    }
  }
}